﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

/*
 客户端方法和服务端方法差不多，大部分注释请参考 服务端代码注释
 */
namespace AsyncSocket1.Client
{
    class Program
    {
        static Socket socketClient;
        static byte[] receiveByte = null;
        static void Main(string[] args)
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5001);
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //开始连接到服务器监听的IP  
            socketClient.BeginConnect(ipe, new AsyncCallback(ConnectCallBack), socketClient);
            //接收数据
            while (true)
            {
                if (socketClient != null && socketClient.Connected)
                {
                    receiveByte = new byte[1024];
                    socketClient.BeginReceive(receiveByte, 0, receiveByte.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socketClient);
                    break;
                }
                Thread.Sleep(50);
            }

            //输入信息
            string inputMsg = string.Empty;
            //接受服务端发送过来的信息
            string receiveMsg = string.Empty;
            while (true)
            {
                if (!socketClient.Connected) continue;

                Console.WriteLine("请输入(输入exit退出对话)：");
                inputMsg = Console.ReadLine();

                if (inputMsg.ToLower() == "exit") break;

                //输入的信息，转换为字节数组
                byte[] byteMsg = Encoding.UTF8.GetBytes(inputMsg);
                socketClient.BeginSend(byteMsg, 0, byteMsg.Length, SocketFlags.None, new AsyncCallback(SendCallback), socketClient);
            }

            Console.Read();
        }

        /// <summary>
        /// 连接成功后的回调函数
        /// </summary>
        /// <param name="iar"></param>
        static void ConnectCallBack(IAsyncResult iar)
        {
            socketClient = iar.AsyncState as Socket;
            socketClient.EndConnect(iar);
        }

        static void ReceiveCallBack(IAsyncResult iar)
        {
            Socket tmpSocket = iar.AsyncState as Socket;
            tmpSocket.EndReceive(iar);

            string receiveMsg = Encoding.UTF8.GetString(receiveByte).TrimEnd('\0');
            Console.WriteLine("服务端说：\n{0}", receiveMsg);
            //因为接受信息后，会顶掉之前的“请输入”提示，此处只是方便提示用户输入
            Console.WriteLine("请输入(输入exit退出对话)：");
            receiveByte = new byte[1024];
            socketClient.BeginReceive(receiveByte, 0, receiveByte.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socketClient);
        }

        /// <summary>
        /// 发送成功后的回调函数
        /// </summary>
        /// <param name="iar"></param>
        static void SendCallback(IAsyncResult iar)
        {
            Socket socketClient = iar.AsyncState as Socket;
            int sendCount = socketClient.EndSend(iar);
            //if (sendCount > 0)
            //{
            //    Console.WriteLine("发送成功，字节数为：{0}", sendCount);
            //}

        }

    }
}
